package com.mofofa.maozy.components.input

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import com.mofofa.maozy.R
import com.mofofa.maozy.base.BaseEditAction
import com.mofofa.maozy.base.BaseFormAction
import com.mofofa.maozy.databinding.ViewMaozyLoginAccountInputBinding
import com.mofofa.maozy.enums.CountryPathEnum
import com.mofofa.maozy.extend.*

/**
<declare-styleable name="MaozyLoginAccountInput">
<attr name="cwlaiTitle" format="string" />
<attr name="cwlaiTextColor" format="color" />
<attr name="cwlaiHint" format="string" />
<attr name="cwlaiDelImageRes" format="reference" />
<attr name="cwlaiDelImageHidden" format="boolean" />
<attr name="cwlaiPreHintHidden" format="boolean" />
</declare-styleable>
 * */
class LoginAccountInput : RelativeLayout, BaseFormAction,
    BaseEditAction {

    lateinit var mMaozyViewMaozyBinding: ViewMaozyLoginAccountInputBinding
    private lateinit var vMaozyRootMaozyView: View

    private var cwlaiTextColor: Int = 0
    private var cwlaiHintColor: Int = 0
    private var cwlaiTitle: String? = null
    private var cwlaiText: String? = null
    private var cwlaiHint: String? = null
    private var cwlaiDelImageRes: Int = 0
    private var cwlaiDelImageHidden: Boolean = false
    private var cwlaiPreHintHidden: Boolean = false
    private var cwlaiPreHintLineHidden: Boolean = false
    private var cwlaiPreHintText: String? = null
    private var cwlaiIsTitleBold: Boolean = true
    private var cwlaiTitleSize: Float = 0F

    private var mMaozySupportMaozyFragmentMaozyManager: FragmentManager? = null

    private var mMaozyTempMaozyInputMaozyValue: String = ""
    private var mMaozyOnMaozyActionMaozyClickMaozyListener: (Int) -> Unit = {}
    private var mMaozyOnMaozyTextMaozyChangedMaozyListener: (String) -> Unit =
        { text -> }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        attrs?.let {
            context?.let { cxt ->
                val array =
                    cxt.obtainStyledAttributes(attrs, R.styleable.LoginAccountInput)
                cwlaiTextColor = array.getColor(
                    R.styleable.LoginAccountInput_cwlaiTextColor,
                    ContextCompat.getColor(cxt, R.color.main_black)
                )
                cwlaiText =
                    array.getString(R.styleable.LoginAccountInput_cwlaiText)

                cwlaiTitle =
                    array.getString(R.styleable.LoginAccountInput_cwlaiTitle)

                cwlaiHintColor = array.getColor(
                    R.styleable.LoginAccountInput_cwlaiHintColor,
                    ContextCompat.getColor(cxt, R.color.input_hint)
                )
                cwlaiHint =
                    array.getString(R.styleable.LoginAccountInput_cwlaiHint)

                cwlaiDelImageRes =
                    array.getResourceId(
                        R.styleable.LoginAccountInput_cwlaiDelImageRes,
                        R.drawable.maozy_close
                    )
                cwlaiDelImageHidden = array.getBoolean(
                    R.styleable.LoginAccountInput_cwlaiDelImageHidden,
                    false
                )

                cwlaiPreHintHidden = array.getBoolean(
                    R.styleable.LoginAccountInput_cwlaiPreHintHidden,
                    false
                )

                cwlaiPreHintLineHidden = array.getBoolean(
                    R.styleable.LoginAccountInput_cwlaiPreHintLineHidden,
                    false
                )

                cwlaiPreHintText =
                    array.getString(R.styleable.LoginAccountInput_cwlaiPreHintText)

                cwlaiIsTitleBold = array.getBoolean(
                    R.styleable.LoginAccountInput_cwlaiIsTitleBold,
                    true
                )

                cwlaiTitleSize = array.getDimension(
                    R.styleable.LoginAccountInput_cwlaiTitleSize,
                    resources.getDimensionPixelSize(
                        R.dimen.sp_14
                    ).toFloat()
                )

                array.recycle()
            }
        }
        context?.let {
            vMaozyRootMaozyView =
                View.inflate(it, R.layout.view_maozy_login_account_input, this)
            mMaozyViewMaozyBinding =
                ViewMaozyLoginAccountInputBinding.bind(vMaozyRootMaozyView)
            initMaozySubviews()
        }
    }

    override fun initMaozySubviews() {
        try {
            mMaozyViewMaozyBinding.textLoinAccountTitle.text = cwlaiTitle
            mMaozyViewMaozyBinding.textLoinAccountTitle.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                cwlaiTitleSize
            )
            if (cwlaiIsTitleBold) {
                mMaozyViewMaozyBinding.textLoinAccountTitle.addMaozyBoldMaozyStyle()
            } else {
                mMaozyViewMaozyBinding.textLoinAccountTitle.addMaozyNormalMaozyStyle()
            }

            mMaozyViewMaozyBinding.editLoinAccount.setText(cwlaiText)
            mMaozyViewMaozyBinding.editLoinAccount.setTextColor(cwlaiTextColor)

            mMaozyViewMaozyBinding.editLoinAccount.hint = (cwlaiHint)
            mMaozyViewMaozyBinding.editLoinAccount.setHintTextColor(cwlaiHintColor)

            mMaozyViewMaozyBinding.imageLoginAccountDel.setImageResource(cwlaiDelImageRes)

            mMaozyViewMaozyBinding.llLoginAccountDelBg.setOnClickListener {
                mMaozyOnMaozyActionMaozyClickMaozyListener.invoke(0)
            }

            mMaozyViewMaozyBinding.imageLoginAccountDel.setOnClickListener {
                mMaozyOnMaozyActionMaozyClickMaozyListener.invoke(0)
            }

            mMaozyViewMaozyBinding.textLoinAccountPreHint.text = cwlaiPreHintText

            if (cwlaiPreHintHidden) {
                mMaozyViewMaozyBinding.textLoinAccountPreHint.visibility = GONE
            } else {
                mMaozyViewMaozyBinding.textLoinAccountPreHint.visibility = VISIBLE
            }

            if (cwlaiPreHintLineHidden) {
                mMaozyViewMaozyBinding.vLoinAccountPreHintLine.visibility = GONE
            } else {
                mMaozyViewMaozyBinding.vLoinAccountPreHintLine.visibility = VISIBLE
            }

            mMaozyViewMaozyBinding.editLoinAccount.setOnFocusChangeListener { _, b ->
                if (!b) {
                    isMaozyCompleted()
                    val gContent = getMaozyContent()
                    if (gContent.isNotBlank()) {
                        if (!gContent.equals(
                                mMaozyTempMaozyInputMaozyValue,
                                false
                            )
                        ) {
                            try {
                                mMaozyTempMaozyInputMaozyValue = gContent
                                recordMaozyInputMaozyEvent(gContent)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                } else {
                    //判断是否显示删除按键
                    val tempContent = getMaozyContent()
                    if (tempContent.isNotBlank()) {
                        if (cwlaiDelImageHidden) {
                            mMaozyViewMaozyBinding.llLoginAccountDelBg.visibility = GONE
                        } else {
                            mMaozyViewMaozyBinding.llLoginAccountDelBg.visibility =
                                VISIBLE
                        }
                        mMaozyViewMaozyBinding.textLoinAccountPreHint.setTextColor(
                            ContextCompat.getColor(
                                context,
                                R.color.main_black
                            )
                        )
                    } else {
                        mMaozyViewMaozyBinding.llLoginAccountDelBg.visibility = GONE
                        mMaozyViewMaozyBinding.textLoinAccountPreHint.setTextColor(
                            ContextCompat.getColor(
                                context,
                                R.color.black_7004
                            )
                        )
                    }
                }
            }
            mMaozyViewMaozyBinding.editLoinAccount.addTextChangedListener(object :
                TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    //判断是否显示删除按键
                    val tempContent = getMaozyContent()
                    if (tempContent.isNotBlank()) {
                        if (cwlaiDelImageHidden) {
                            mMaozyViewMaozyBinding.llLoginAccountDelBg.visibility = GONE
                        } else {
                            mMaozyViewMaozyBinding.llLoginAccountDelBg.visibility =
                                VISIBLE
                        }
                    } else {
                        mMaozyViewMaozyBinding.llLoginAccountDelBg.visibility = GONE
                    }
                    //回调
                    mMaozyOnMaozyTextMaozyChangedMaozyListener.invoke(
                        tempContent
                    )
                }
            })

            mMaozyViewMaozyBinding.llLoginAccountDelBg.setOnClickListener {
                mMaozyViewMaozyBinding.editLoinAccount.setText("")
            }
            mMaozyViewMaozyBinding.imageLoginAccountDel.setOnClickListener {
                mMaozyViewMaozyBinding.editLoinAccount.setText("")
            }

            //增加星号显示
            mMaozyViewMaozyBinding.textLoinAccountTitle.addMaozyHighlightMaozyStyle(
                mutableListOf("*"),
                ContextCompat.getColor(context, R.color.main_red)
            )

        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    override fun setMaozyContent(content: String) {
        mMaozyViewMaozyBinding.editLoinAccount.setText(content)
    }

    fun getMaozyContent(): String {
        return mMaozyViewMaozyBinding.editLoinAccount.text.toString().trim()
    }

    fun isMaozyCompleted(): Boolean {
        val gcontent = getMaozyContent()
        if (gcontent.isBlank()) {
            mMaozyViewMaozyBinding.rlLoinAccountBg.setBackgroundResource(R.drawable.maozy_form_input_error)
            mMaozyViewMaozyBinding.textLoginAccountErrTip.visibility = VISIBLE
            return false
        }

        mMaozyViewMaozyBinding.textLoginAccountErrTip.visibility = GONE
        mMaozyViewMaozyBinding.rlLoinAccountBg.setBackgroundResource(R.drawable.maozy_form_input)
        return true
    }

    fun isMaozyCompletedMaozySlient(): Boolean {
        val gcontent = getMaozyContent()
        if (gcontent.isBlank()) {
            return false
        }
        return true
    }


    override fun toMaozyBeMaozyFocusMaozyPointMaozyAndMaozyShowMaozyInputMaozyKeyboard() {
        try {
            mMaozyViewMaozyBinding.editLoinAccount.isFocusable = true
            mMaozyViewMaozyBinding.editLoinAccount.isFocusableInTouchMode = true
            mMaozyViewMaozyBinding.editLoinAccount.requestFocus()
            Handler(Looper.getMainLooper()).postDelayed({
                context?.let { cxt ->
                    try {
                        val inputMethodManager: InputMethodManager =
                            cxt.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                        inputMethodManager.showSoftInput(
                            mMaozyViewMaozyBinding.editLoinAccount,
                            0
                        )
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }, 300)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun toMaozyBeMaozyFocusMaozyPoint() {
        try {
            mMaozyViewMaozyBinding.editLoinAccount.isFocusable = true
            mMaozyViewMaozyBinding.editLoinAccount.isFocusableInTouchMode = true
            mMaozyViewMaozyBinding.editLoinAccount.requestFocus()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun setMaozyInputMaozyHint(hint: String) {
        val hintFormat = hint.toMaozyPhoneMaozyNumberMaozyInputMaozyHint()
        mMaozyViewMaozyBinding.editLoinAccount.hint = hintFormat
    }

    fun setMaozyPreMaozyHint(hint: String) {
        mMaozyViewMaozyBinding.textLoinAccountPreHint.text = hint
    }

    override fun setMaozyFragmentMaozyManager(manager: FragmentManager) {
        mMaozySupportMaozyFragmentMaozyManager = manager
    }

    override fun setMaozyOnMaozyActionMaozyClickMaozyListener(listener: (Int) -> Unit) {
        mMaozyOnMaozyActionMaozyClickMaozyListener = listener
    }

    override fun setMaozyOnMaozyTextMaozyChangedMaozyListener(listener: (String) -> Unit) {
        mMaozyOnMaozyTextMaozyChangedMaozyListener = listener
    }

    override fun setMaozyTitle(title: String) {

    }

    override fun setMaozyDetail(detail: String) {

    }

    override fun setMaozyHint(hint: String) {
        setMaozyInputMaozyHint(hint)
    }

    override fun setMaozyDetailMaozyColor(detailColor: Int) {

    }

    override fun setMaozyTitleMaozyColor(titleColor: Int) {

    }

    fun cleanMaozy() {
        mMaozyViewMaozyBinding.editLoinAccount.setText(null)
    }

    @SuppressLint("SetTextI18n")
    fun updateMaozyLanguage(country: String, customer: String) {
        mMaozyViewMaozyBinding.editLoinAccount.hint = customer
        when (country) {
            CountryPathEnum.maozyfcfa.name -> {
                mMaozyViewMaozyBinding.textLoinAccountPreHint.text = "+225"
            }
            CountryPathEnum.maozygha.name -> {
                mMaozyViewMaozyBinding.textLoinAccountPreHint.text = "+233"
            }
            CountryPathEnum.maozynaira.name -> {
                mMaozyViewMaozyBinding.textLoinAccountPreHint.text = "+234"
            }
            CountryPathEnum.maozyksh.name -> {
                mMaozyViewMaozyBinding.textLoinAccountPreHint.text = "+254"
            }
            CountryPathEnum.maozyugx.name -> {
                mMaozyViewMaozyBinding.textLoinAccountPreHint.text = "+256"
            }
            CountryPathEnum.maozyvnd.name -> {
                mMaozyViewMaozyBinding.textLoinAccountPreHint.text = "+84"
            }
        }
    }

}